package com.timeshare.controller;

import com.timeshare.common.Result;
import com.timeshare.dto.ChatMessageDTO;
import com.timeshare.entity.ChatMessage;
import com.timeshare.service.ChatService;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 聊天控制器
 */
@Controller
public class ChatController {
    
    private final SimpMessagingTemplate messagingTemplate;
    private final ChatService chatService;
    
    public ChatController(SimpMessagingTemplate messagingTemplate, ChatService chatService) {
        this.messagingTemplate = messagingTemplate;
        this.chatService = chatService;
    }
    
    @MessageMapping("/chat/send")
    public void sendMessage(@Payload ChatMessageDTO message) {
        try {
            // 保存消息到数据库
            ChatMessage chatMessage = chatService.saveMessage(message);
            
            // 发送给接收者
            messagingTemplate.convertAndSendToUser(
                message.getReceiverId().toString(),
                "/queue/messages",
                chatMessage
            );
            
            // 发送给发送者（确认）
            messagingTemplate.convertAndSendToUser(
                message.getSenderId().toString(),
                "/queue/messages",
                chatMessage
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @GetMapping("/chat/history")
    @ResponseBody
    public Result<List<ChatMessage>> getChatHistory(
            @RequestParam Long userId1,
            @RequestParam Long userId2,
            @RequestParam(defaultValue = "50") Integer limit) {
        try {
            List<ChatMessage> messages = chatService.getChatHistory(userId1, userId2, limit);
            return Result.success(messages);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    @GetMapping("/chat/unread-count")
    @ResponseBody
    public Result<Integer> getUnreadCount(@RequestParam Long userId) {
        try {
            Integer count = chatService.getUnreadCount(userId);
            return Result.success(count);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    @PostMapping("/chat/mark-read")
    @ResponseBody
    public Result<String> markAsRead(@RequestParam Long userId, @RequestParam Long senderId) {
        try {
            chatService.markAsRead(userId, senderId);
            return Result.success("标记已读成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    @PostMapping("/chat/recall")
    @ResponseBody
    public Result<String> recallMessage(@RequestParam Long messageId, @RequestParam Long userId) {
        try {
            chatService.recallMessage(messageId, userId);
            return Result.success("撤回成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}

